package hoang.hut.app.tool.raw;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

public class RawFile {

	/**
	 * load image to Asset folder
	 * 
	 * @param imv
	 * @param filename
	 * @param context
	 */
	public void loadDataFromAsset(ImageView imv, String filename,
			Context context) {
		try {

			InputStream is = ((Activity) context).getAssets().open(filename);
			Drawable d = Drawable.createFromStream(is, null);
			imv.setImageDrawable(d);
		} catch (IOException ex) {
			return;
		}
	}
	/**
	 * doc file tu res/raw
	 * 
	 * @param context
	 * @param rawfile: id cua file R.raw.filename
	 * @return
	 */
	public String getStringToFileRaw(Context context, int rawfile){
		try {
			InputStream is = context.getResources().openRawResource(rawfile);
			return readStringFromStream(is);
		} catch (Exception e) {
		}
		return null;
		
	}
	/**
	 * doc file tu assets
	 * 
	 * @param context
	 * @param filename: ten file: tenfile.txt
	 * @return
	 */
	public String getStringToFileAssets(Context context, String filename) {

		try {
			InputStream is = ((Activity) context).getAssets().open(filename);
			return readStringFromStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;

	}
	/**
	 * convert inputStirng to String
	 * 
	 * @param stream
	 * @return
	 * @throws IOException
	 */
	public String readStringFromStream(InputStream stream) throws IOException {
		InputStreamReader isReader = new InputStreamReader(stream,
				Charset.forName("utf-8"));
		BufferedReader br = new BufferedReader(isReader);
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line).append("\n");
		}
		return sb.toString();
	}
}
